import threading
import time
from typing import List, Optional

from loguru import logger

from schemas.Page import PageCreate
from schemas.Activity import Activity
from sqlalchemy.orm import Session
from services.ActivityServe import ActivityServe

class ActivityCache:
    def __init__(self, db: Session, page: PageCreate, refresh_interval=60, timeout=120, max_idle_refresh=5, force_refresh_interval=3600):
        """
        :param db: 数据库会话
        :param page: 查询参数
        :param refresh_interval: 定时刷新间隔（秒）
        :param timeout: 缓存超时时间（秒）
        :param max_idle_refresh: 最大无请求定时刷新次数，超过后休眠
        :param force_refresh_interval: 强制刷新间隔（秒），无论是否有请求都会刷新
        """
        self.db = db
        self.page = page
        self.refresh_interval = refresh_interval
        self.timeout = timeout
        self.max_idle_refresh = max_idle_refresh
        self.force_refresh_interval = force_refresh_interval

        self._cache: List[Activity] = []
        self._last_update = 0
        self._last_access = 0
        self._idle_refresh_count = 0
        self._lock = threading.Lock()
        self._timer = None
        self._active = True
        logger.info("start 活动缓存初始化完成")
        self._start_timer()

    def _start_timer(self):
        if self._timer:
            self._timer.cancel()
        self._timer = threading.Timer(self.refresh_interval, self._refresh_timer)
        self._timer.daemon = True
        self._timer.start()

    def _refresh_timer(self):
        with self._lock:
            if not self._active:
                return
            now = time.time()
            # 如果长时间没人访问，休眠
            if self._idle_refresh_count >= self.max_idle_refresh:
                self._active = False
                return
                
            # 检查是否需要强制刷新（无论是否有请求）
            if now - self._last_update >= self.force_refresh_interval:
                logger.info("start 强制刷新缓存数据...")
                self._refresh_cache()
            else:
                self._refresh_cache()
                
            self._idle_refresh_count += 1
        self._start_timer()

    def _refresh_cache(self):
        data = ActivityServe.getList(self.db, self.page)
        if data is not None:
            self._cache = data
            self._last_update = time.time()

    def get_activities(self) -> List[Activity]:
        with self._lock:
            now = time.time()
            self._last_access = now
            # 有请求，重置休眠倒计时
            self._idle_refresh_count = 0
            if not self._active:
                self._active = True
                self._start_timer()
            # 判断缓存是否超时
            if now - self._last_update > self.timeout:
                logger.info("start 活动缓存已超时，正在刷新...")
                self._refresh_cache()
            else:
                logger.info("start 活动缓存未超时，直接返回缓存数据...")
                
            # 检查是否需要强制刷新
            if now - self._last_update > self.force_refresh_interval:
                logger.info("start 达到强制刷新时间，正在刷新缓存...")
                self._refresh_cache()
                
            return self._cache.copy()

    def stop(self):
        if self._timer:
            self._timer.cancel()
            self._timer = None
        self._active = False

# 用法示例（建议在服务层单例管理 ActivityCache 实例）：
# activity_cache = ActivityCache(db, page)
# 活动列表获取：activity_cache.get_activities()
